<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use App\Admin\ContractDetail;

class ContractDetailController extends Controller
{


    /* 合同详细信息批量添加 */
    public function add(Request $request)
    {
        //获取批次的id
        $id = $request->id;
        //获取批次号
        $batch_num = DB::table('a_contract')->where('id', $id)->value('batchNum');
        //获取批次的概要信息
        $data_gaiyao = DB::table('a_contract_gaiyao')->where('a_contract_id', $id)->get();
        if ($data_gaiyao->isEmpty()) {
            return '此批次内容是空的';
        }

        $data_insert = [];
        $data_insert2 = [];
        foreach ($data_gaiyao as $val) {
            $count = $val->count;

            //获取样品名 与 试验数据表、试验标准表对应关系的一条记录
            $data_vs = DB::table('a_sample_vs_valuetable')->where('sample_name', $val->sample_name)->first();
            if (!$data_vs) {
                # 如果$data_vs 为 null
                return "在数据库的 <b>a_sample_vs_valuetable</b> 表中未查到 <b>{$val->sample_name}</b> 的记录";
            }
            //存储试验数据的表名
            $table_name_val = $data_vs->table_name_val;
            //存储试验标准的表名
            $table_name_bz = $data_vs->table_name_bz;
            //查询执行标准
            switch ($val->sample_name) {
                case '带电作业用绝缘靴（鞋）':
                    # code...

                    //取出试验标准
                    $biaozhun_data = DB::table($table_name_bz)->where('biaozhun', $val->biaozhun)->where('class1', $val->class1)->where('voltage_level', $val->voltage_level)->first();
                    // dd( $biaozhun_data);
                    if (!$biaozhun_data) {
                        # 如果$biaozhun_data 为 null
                        return "在数据库的 <b>{$table_name_bz}</b> 表中未查到<br>样品名称为 <b>{$val->sample_name}</b>，电压等级为 <b>{$val->voltage_level}</b>，分类为 <b>{$val->class1}</b> 的记录";
                    }
                    break;

                default:
                    # code...
                    break;
            }

            $index = $val->index;
            for ($i = 0; $i < $count; $i++) {
                $str_suf = sprintf('%03d', $index++);
                $bar_code = $batch_num . $str_suf;
                //构建要插入的数据
                $data_insert[] = [
                    'bar_code' => $bar_code,
                    'a_contract_id' => $id,
                    'a_contract_gaiyao_id' => $val->id,
                    'sample_name' => $val->sample_name,
                    'class1' => $val->class1,
                    'voltage_level' => $val->voltage_level,
                    'biaozhun' => $val->biaozhun,
                    'items' => $val->items,
                    'danwei' => $val->danwei
                ];


                $data_insert2[] = [
                    'bar_code' => $bar_code,
                    'parm1' => $biaozhun_data->parm1,
                    'parm2' => $biaozhun_data->parm2,
                    'parm3' => $biaozhun_data->parm3,
                    'cycle' => $biaozhun_data->cycle
                ];
            }
        }
        //插入数据    insert 返回true 或 false
        $result = DB::table('a_contract_detail')->insert($data_insert);
        $result2 = DB::table($table_name_val)->insert($data_insert2);
        if ($result && $result2) {
            //改变批次的状态
            $data_status = ['status' => '1'];
            $result3 = DB::table('a_contract')->where('id', $id)->update($data_status);
        }
        return $result3 ? '1' : '0';
    }

    /* 合同详细信息展示 */
    public function index(Request $request)
    {
        //获取批次的id
        $id = $request->id;
        //获取批次的详细信息
        $data = DB::table('a_contract_detail')->where('a_contract_id', $id)->get();
        return view('admin.contractDetail.index', compact('data'));
    }

    /* 合同的详细信息展示+信息录入 */
    public function indexInfoLuru(Request $request)
    {
        if ($request->expectsJson()) {
            if ($request->isMethod('POST')) {
                $post_data = $request->only(['self_num', 'guige_xinghao', 'brand', 'manufacturer', 'production_date', 'fuhexing']);
                $result = ContractDetail::where('id', $request->detail_id)->update($post_data);
                return $result >= 0 ? '1' : '0';
            } else {
                //获取批次的id
                $id = $request->id;
                $contractDetail = new ContractDetail();
                $result = $contractDetail->getTableData($request->all(), null, null, [['a_contract_id', '=', $id]]);
                return response()->json($result);
            }
        } else {
            $contractInfo = DB::table('a_contract')->select('client_name')->find($request->id);

            return view('admin.contractDetail.indexInfoLuru', compact('contractInfo'));
        }
    }
    /* 合同的详细信息展示+结果录入 */
    public function indexResLuru(Request $request)
    {
        if ($request->expectsJson()) {
            if ($request->isMethod('POST')) { } else {
                //获取批次的id
                $id = $request->id;
                $contractDetail = new ContractDetail();
                $result = $contractDetail->getTableData($request->all(), null, null, [['a_contract_id', '=', $id], ['manager_id', '=', auth('admin')->user()->id]]);
                return response()->json($result);
            }
        } else {
            $contractInfo = DB::table('a_contract')->select('client_name')->find($request->id);

            return view('admin.contractDetail.indexResLuru', compact('contractInfo'));
        }
    }

    /* 合同的详细信息展示(条形码打印) */
    public function indexPrintBarCode(Request $request)
    {
        //获取批次的id
        $id = $request->id;
        if ($request->expectsJson()) {
            $contractDetail = new ContractDetail();
            $result = $contractDetail->getTableData($request->all(), null, null, [['a_contract_id', '=', $id]]);
            return response()->json($result);
        } else {
            //获取批次的客户名称
            $client_name = DB::table('a_contract')->where('id', $id)->value('client_name');
            return view('admin.contractDetail.indexPrintBarCode', compact('client_name'));
        }
    }

    //单个提交，结果录入后
    public function oneSubmit(Request $request)
    {
        $id = $request->id;

        //  update 返回受影响的行数
        $res1 = DB::table('a_contract_detail')->where('id', $id)->increment('submit_times', 1, ['status' => '1']);
        // 提交后检查未提交的记录数
        $res3 = DB::table('a_contract_detail')->where('a_contract_id', $request->batch_id)->where('status', '0')->count();
        //如果为0，说明本批次已全部提交，此时改变contract的状态
        if ($res3 === 0) {
            $res4 = DB::table('a_contract')->where('id', $request->batch_id)->update(['status' => '8']);
        }

        //由于框架自身不支持响应bool值，所以转化一种形式
        return $res1 >= 0 ? '1' : '0';
    }

    //批量提交，结果录入后
    public function batchSubmit(Request $request)
    {
        //  update 返回受影响的行数
        $res1 = DB::table('a_contract_detail')->whereIn('id', $request->checkID)->increment('submit_times', 1, ['status' => '1']);
        // 提交后检查未提交的记录数
        $res3 = DB::table('a_contract_detail')->where('a_contract_id', $request->batch_id)->where('status', '0')->count();
        //如果为0，说明本批次已全部提交，此时改变contract的状态
        if ($res3 === 0) {
            $res4 = DB::table('a_contract')->where('id', $request->batch_id)->update(['status' => '8']);
        }

        //由于框架自身不支持响应bool值，所以转化一种形式
        return $res1 >= 0 ? '1' : '0';
    }

    /* 合同的详细信息展示（审核） */
    public function indexCheck(Request $request)
    {
        if ($request->expectsJson()) {
            if ($request->isMethod('POST')) {
                //
            } else {
                //获取批次的id
                $id = $request->id;
                $contractDetail = new ContractDetail();
                $result = $contractDetail->getTableData($request->all(), 'manager:id,realname', null, [['a_contract_id', '=', $id]]);
                return response()->json($result);
            }
        } else {
            $contractInfo = DB::table('a_contract')->select('client_name')->find($request->id);

            return view('admin.contractDetail.indexCheck', compact('contractInfo'));
        }
    }

    /* 合同的详细信息展示（打印合格证） */
    public function indexPrintPassedCard(Request $request)
    {
        if ($request->expectsJson()) {
            if ($request->isMethod('POST')) {
                //
            } else {
                //获取批次的id
                $id = $request->id;
                // $contractDetail = new ContractDetail();
                // $result = $contractDetail->getTableData($request->all(), 'manager:id,realname,partner', null, [['a_contract_id', '=', $id]]);
                // return response()->json($result);


                $data = ContractDetail::with('manager:id,realname,partner')->where('a_contract_id', $id)->get();
                $jsonData['data'] = $data;
                return response()->json($jsonData);
            }
        } else {
            $contractInfo = DB::table('a_contract')->select('client_name')->find($request->id);

            return view('admin.contractDetail.indexPrintPassedCard', compact('contractInfo'));
        }
    }

    //单个审核
    public function oneCheck(Request $request)
    {
        // sleep(5);
        $id = $request->id;
        //  update 返回受影响的行数
        $res1 = DB::table('a_contract_detail')->where('id', $id)->increment('check_times', 1, ['status' => $request->status]);
        // 审核后检查 未审核通过 的记录数
        $res3 = DB::table('a_contract_detail')->where('a_contract_id', $request->batch_id)->where('status', '<>', '2')->count();
        //如果为0，说明本批次已全部审核通过，此时改变contract的状态
        if ($res3 === 0) {
            $res4 = DB::table('a_contract')->where('id', $request->batch_id)->update(['status' => '11']);
        } else {
            $res4 = DB::table('a_contract')->where('id', $request->batch_id)->update(['status' => '8']);
        }

        //由于框架自身不支持响应bool值，所以转化一种形式
        return $res1 >= 0 ? '1' : '0';
    }

    //批量审核
    public function batchCheck(Request $request)
    {

        //  update 返回受影响的行数
        $res1 = DB::table('a_contract_detail')->whereIn('id', $request->checkID)->increment('check_times', 1, ['status' => $request->status]);
        // 审核后检查 未审核通过 的记录数
        $res3 = DB::table('a_contract_detail')->where('a_contract_id', $request->batch_id)->where('status', '<>', '2')->count();
        //如果为0，说明本批次已全部审核通过，此时改变contract的状态
        if ($res3 === 0) {
            $res4 = DB::table('a_contract')->where('id', $request->batch_id)->update(['status' => '11']);
        } else {
            $res4 = DB::table('a_contract')->where('id', $request->batch_id)->update(['status' => '8']);
        }

        //由于框架自身不支持响应bool值，所以转化一种形式
        return $res1 >= 0 ? '1' : '0';
    }

    //扫描二维码后，查询样品的基础信息
    public function getInfoById(Request $request)
    {
        //样品详细信息的id
        $id = $request->id;
        $data = DB::table('a_contract_detail')->select('self_num', 'guige_xinghao', 'brand', 'manufacturer', 'production_date')->find($id);
        $res = null;

        if ($data) {
            # 查到了结果
            $res = response()->json($data);
        } else {
            # 未查到结果
            $res = 'false';
        }
        return $res;
    }
}
